package com.stars.services.impl.system;
import com.github.pagehelper.PageInfo;
import com.stars.entity.system.SysCompanyEntity;
import com.stars.services.system.SysCompanyAccessServices;
import com.stars.dao.mapper.system.SysCompanyMapper;
import com.stars.entity.dto.system.SysCompanyDTO;

import java.util.List;
import com.stars.common.base.BaseConstant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.stars.common.SpecialSymbolUtils;
import org.apache.commons.lang3.StringUtils;
import com.stars.common.base.ResultMsg;
import com.stars.entity.ListPage;
import com.github.pagehelper.PageHelper;
import com.stars.services.impl.BaseAccessServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Title: 公司管理 业务逻辑
 * @author dj
 * @date 2019-10-10 20:48:07
 * @version V1.0
 *
 */
@Service
public class SysCompanyAccessServicesImpl  extends BaseAccessServiceImpl<SysCompanyMapper , SysCompanyEntity> implements  SysCompanyAccessServices {
    @Autowired
    private SysCompanyMapper  sysCompanyMapper;

    @Override
    public List<SysCompanyDTO> findTreeList(SysCompanyDTO treeDTO) throws Exception {
        List<SysCompanyDTO> treeList = new ArrayList<>();
        //TODO 查询字段
        if(StringUtils.isEmpty(treeDTO.getCompanyName())){
            treeList = sysCompanyMapper.findByPid(BaseConstant.ROOT);
        }else {
            treeList = sysCompanyMapper.findByName(SpecialSymbolUtils.convert(treeDTO.getCompanyName()));
        }
        List<SysCompanyDTO> list = sysCompanyMapper.findTreeList(treeList);
        return getTree(list);
    }

    private List<SysCompanyDTO> getTree(List<SysCompanyDTO> list) {
        //首先将list转map映射
        Map<String,SysCompanyDTO> map = new HashMap<>();
        List<SysCompanyDTO> treeList = new ArrayList<>();
        //循环生成Tree
        for (SysCompanyDTO dto: list){
            map.put(dto.getId(),dto);
            if(dto.getLayer() < 3){
                dto.setExpanded(true);
            }
            //如果存在父节点，那么获取父节点，并将自己加入父节点
            if(StringUtils.isNoneEmpty(dto.getPid()) && !BaseConstant.ROOT.equals(dto.getPid()) ){
                map.get(dto.getPid()).getChildren().add(dto);
            }else {
                treeList.add(dto);
            }
        }
        return treeList;
    }


    /**
     * 分页查询
     * @param pageNum 查询参数 起始页，大小。
     * @return
     */
    @Override
    public PageInfo<SysCompanyDTO> pageList(Integer pageNum, Integer pageSize, SysCompanyDTO command) throws Exception{
        ListPage<SysCompanyDTO> listPage = new ListPage<>(pageNum, pageSize, command);
        PageHelper.startPage(pageNum, pageSize);
        List<SysCompanyDTO> list = sysCompanyMapper.pageQuerySysCompany(listPage);
        PageInfo<SysCompanyDTO> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }
}
